//
//  EF_WKWebView.m
//  J智现场
//
//  Created by song on 2017/11/13.
//  Copyright © 2017年 王长飞. All rights reserved.
//

#import "InformationController.h"
#import <WebKit/WebKit.h>
#import "InformationModel.h"
#import "AddStudyTimeModel.h"

@interface InformationController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,BaseModelProtocol>

@property (nonatomic, strong) UILabel *titlelab;
@property (nonatomic, strong) UIView *studeyBgView;
@property (nonatomic, strong) UILabel *alreadyStudyLab;
@property (nonatomic, strong) UILabel *needStudyLab;
@property (nonatomic, strong) UILabel *leftStudyLab;

//iOS8之后苹果推荐使用WKWebView替代UIWebView
@property (nonatomic, strong) WKWebView *webView;

@property(nonatomic,strong)UIProgressView *progressView;
@property(nonatomic,strong)InformationModel *infoModel;
@property(nonatomic,strong)NSArray *fontArray;
@property(nonatomic,strong)NSArray *lineHeightArray;
@property(nonatomic,strong)InformationData *infoData;

@property (nonatomic,strong) NSTimer  *studyTimer ;
@property (nonatomic,assign) int alreadyStudyTime ;
@property (nonatomic,assign) int needStudyTime ;
@property (nonatomic,assign) int leftStudyTime ;

@property(nonatomic,strong)AddStudyTimeModel *addStudyModel;

@end

@implementation InformationController{
    CGFloat webContentHeight;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //移除监听
    [self.webView removeObserver:self forKeyPath:@"loading"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
//    [self.webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
    
    if (self.studyTimer){
        [self.studyTimer invalidate];
        self.studyTimer = nil ;
    }
    
    NSString *isShowStudyArea = [NSString stringWithFormat:@"%@",self.infoData.isShowStudyArea];
    if(ISEqual(isShowStudyArea,@"1")) {
        [self.addStudyModel addStudyTimeWith:self.secondMenu alreadyStudyTime:self.alreadyStudyTime];
    }
}

- (void)initView
{
    [self.navBarView addTitle:@"详情"];
    [super initView];
    self.view.backgroundColor = [UIColor whiteColor];

    [self.infoModel getInformationDataWith:self.secondMenu];
    webContentHeight = 80;
    NSLog(@"<<<<<%f",SCREEN_WIDTH);
}

- (void)getDataFinish:(BaseModel *)baseModel netResponse:(BaseResponse *)response{
    if([baseModel isKindOfClass:[InformationModel class]]){
        InformationResponse *resp = (InformationResponse *)response;
        InformationData *data = resp.resObject;
        self.infoData = data;
        self.titleString = data.title;
        if(!ISEMPTY(data.sourceUrl)){
            self.urlString = data.sourceUrl;
        }else{
            self.htmlString = data.detail;
        }
        [self setUpComponet];
    }else if([baseModel isKindOfClass:[AddStudyTimeModel class]]){}
}

- (void)setUpComponet{
    
    [self addTitle];
    [self addStudyView];
    [self creatWebView];
    [self creatProgressView];
    //添加KVO监听
    [self.webView addObserver:self
                   forKeyPath:@"loading"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"title"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"estimatedProgress"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
//    [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)addStudyView{
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, _titlelab.bottom+15, SCREEN_WIDTH-30, 30)];
    _studeyBgView = bgView;
    bgView.backgroundColor = UIColorFromRGB1(0xF7E4CE);
    [self.view addSubview:bgView];
    
    NSString *isShowStudyArea = [NSString stringWithFormat:@"%@",self.infoData.isShowStudyArea];
    if(!ISEqual(isShowStudyArea,@"1")) {
        _studeyBgView.height = 0;
        return;
    }
    
    self.alreadyStudyTime = [self.infoData.alreadyStudyTime intValue];
    int alreadyMinutes = self.alreadyStudyTime / 60;
    int alreadySeconds = self.alreadyStudyTime % 60;
    UILabel *alreadyStudyLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, bgView.width/3, bgView.height)];
    _alreadyStudyLab = alreadyStudyLab;
    alreadyStudyLab.text = [NSString stringWithFormat:@"已学习：%02d:%02d",alreadyMinutes,alreadySeconds];
    alreadyStudyLab.textColor = kTitleColor_midden;
    alreadyStudyLab.font = [UIFont boldSystemFontOfSize:11];
    alreadyStudyLab.textAlignment = NSTextAlignmentCenter;
    [bgView addSubview:alreadyStudyLab];
    
    self.needStudyTime = [self.infoData.needStudyTime intValue];
    int needMinutes = self.needStudyTime / 60;
    int needSeconds = self.needStudyTime % 60;
    UILabel *needStudyLab = [[UILabel alloc] initWithFrame:CGRectMake(alreadyStudyLab.right, 0, bgView.width/3, bgView.height)];
    _needStudyLab = needStudyLab;
    needStudyLab.text = [NSString stringWithFormat:@"需学习：%02d:%02d",needMinutes,needSeconds];
    needStudyLab.textColor = kTitleColor_midden;
    needStudyLab.font = [UIFont boldSystemFontOfSize:11];
    needStudyLab.textAlignment = NSTextAlignmentCenter;
    [bgView addSubview:needStudyLab];
    
    int leftStudyTime = self.needStudyTime - self.alreadyStudyTime;
    int leftMinutes = leftStudyTime / 60;
    int leftSeconds = leftStudyTime % 60;
    UILabel *leftStudyLab = [[UILabel alloc] initWithFrame:CGRectMake(needStudyLab.right, 0, bgView.width/3, bgView.height)];
    _leftStudyLab = leftStudyLab;
    leftStudyLab.text = [NSString stringWithFormat:@"还剩：%02d:%02d",leftMinutes,leftSeconds];
    leftStudyLab.textColor = kTitleColor_midden;
    leftStudyLab.font = [UIFont boldSystemFontOfSize:11];
    leftStudyLab.textAlignment = NSTextAlignmentCenter;
    [bgView addSubview:leftStudyLab];
    
    if(self.alreadyStudyTime < self.needStudyTime){
        self.studyTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFire) userInfo:nil repeats:YES];
        [self.studyTimer fire];
    }
}

- (void)timerFire
{
    self.alreadyStudyTime++;
    if(self.alreadyStudyTime == self.needStudyTime){
        [EFShowView showText:@"学习完成"];
        self.alreadyStudyLab.text = [NSString stringWithFormat:@"已学习：%02d:%02d",self.needStudyTime / 60,self.needStudyTime % 60];
        self.leftStudyLab.text = @"还剩：0:00";
        [self.studyTimer invalidate]; self.studyTimer = nil;
    }else{
        self.alreadyStudyLab.text = [NSString stringWithFormat:@"已学习：%02d:%02d",self.alreadyStudyTime / 60,self.alreadyStudyTime % 60];
        self.leftStudyLab.text = [NSString stringWithFormat:@"还剩：%02d:%02d",(self.needStudyTime-self.alreadyStudyTime) / 60,(self.needStudyTime-self.alreadyStudyTime) % 60];
    }
}

- (void)goback{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        NSLog(@"back");
    }
}
-(void)gofarward{
    if ([self.webView canGoForward]) {
        [self.webView goForward];
    }
}

-(void)creatProgressView{
//    self.progressView = [[UIProgressView alloc]initWithFrame:self.view.bounds];
    self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, KNavFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT-KNavFullHeight)];
//    self.progressView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.progressView];
}
//创建webView
-(void)creatWebView{
    
    WKWebViewConfiguration *config = [WKWebViewConfiguration new];
    //初始化偏好设置属性：preferences
    config.preferences = [WKPreferences new];
    //The minimum font size in points default is 0;
    config.preferences.minimumFontSize = 10;
    //是否支持JavaScript
    config.preferences.javaScriptEnabled = YES;
    //不通过用户交互，是否可以打开窗口
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    //通过JS与webView内容交互
    config.userContentController = [WKUserContentController new];
    // 注入JS对象名称senderModel，当JS通过senderModel来调用时，我们可以在WKScriptMessageHandler代理中接收到
    [config.userContentController addScriptMessageHandler:self name:@"senderModel"];
//    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(15, _studeyBgView.bottom+20, SCREEN_WIDTH-30, SCREEN_HEIGHT-_studeyBgView.bottom-20) configuration:config];
    if(!ISEqual(self.titleString, @"平台介绍")) webContentHeight = SCREEN_HEIGHT-_studeyBgView.bottom-20;
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(15, _studeyBgView.bottom+20, SCREEN_WIDTH-30, webContentHeight) configuration:config];
    self.webView.backgroundColor = [UIColor whiteColor];

    if (!ISEMPTY(self.htmlString)) {
        [self loadHTMLString];
    }
    else{
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
    }
    [self.view addSubview:self.webView];
    
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
}

- (void)loadHTMLString{
   // NSString *jsString = [NSString stringWithFormat:@"<html> \n"
   //                              "<head> \n"
   //                              "<style type=\"text/css\"> \n"
   //                              "body {font-size: %f; font-family: \"%s\"; color: %@;}\n"
   //                              "</style> \n"
   //                              "</head> \n"
   //                              "<body>%@</body> \n"
   //                              "</html>", [@"50" floatValue], "arial", @"#666666",self.htmlString];
   for (NSString *fontStr in self.fontArray) {
       if([self.htmlString containsString:fontStr]){
           NSString *temp = [self.htmlString stringByReplacingOccurrencesOfString:fontStr withString:@"font-size: 40px"];
           self.htmlString = temp;
       }
   }
   if([self.htmlString containsString:@"line-height"]){
       for (NSString *lineHeightStr in self.lineHeightArray) {
           if([self.htmlString containsString:lineHeightStr]){
               NSString *temp = [self.htmlString stringByReplacingOccurrencesOfString:lineHeightStr withString:@"line-height: 50px"];
               self.htmlString = temp;
           }
       }
   }
  
   [self.webView loadHTMLString:self.htmlString baseURL:nil];

}

#pragma mark - KVO监听函数
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
    }else if([keyPath isEqualToString:@"loading"]){
        NSLog(@"loading");
    }
    else if ([keyPath isEqualToString:@"estimatedProgress"]){
        //estimatedProgress取值范围是0-1;
        self.progressView.progress = self.webView.estimatedProgress;
    }
    else if([keyPath isEqualToString:@"contentSize"]){
        //更具内容的高重置webView视图的高度
        NSLog(@">>>>>>>>>>>>>>>>>>>>>");
        NSLog(@"Height is changed! new=%@", [change valueForKey:NSKeyValueChangeNewKey]);
        NSLog(@"tianxia :%@",NSStringFromCGSize(self.webView.scrollView.contentSize));
        CGFloat newHeight = self.webView.scrollView.contentSize.height;
        NSLog(@"newHeight = %f",newHeight);
        [self resetWebViewFrameWithHeight:newHeight];

        if(self.webView.estimatedProgress>=1){
            NSLog(@"lastnewHeight = %f",newHeight);
        }
//        float leftHeight = SCREEN_HEIGHT-_studeyBgView.bottom-20;
    }
    
    if (!self.webView.loading) {
        [UIView animateWithDuration:0.5 animations:^{
            self.progressView.alpha = 0;
        }];
    }
}

-(void)resetWebViewFrameWithHeight:(CGFloat)height{
    /**去掉这个if 是因为KVO 监听的时候有时候网页会由原来的大值变小值 额**/
//    if (CGRectGetHeight(self.wkWebView.frame) == CGRectGetHeight(self.view.frame)) {
//        //如果高度已经达到最高，那么就不用设置，只有记录一下
//        webContentHeight = height;
//    }else{
    float leftHeight = SCREEN_HEIGHT-_studeyBgView.bottom-20;
        //如果是新高度，那就重置
        if (height != webContentHeight) {
            if(height >= leftHeight){
                self.webView.height = leftHeight;
            }else{
                self.webView.height = height;
            }
            webContentHeight = height;
        }
//    }
}


#pragma mark - WKScriptMessageHandler
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    //这里可以通过name处理多组交互
    if ([message.name isEqualToString:@"senderModel"]) {
        //body只支持NSNumber, NSString, NSDate, NSArray,NSDictionary 和 NSNull类型
        NSLog(@"%@",message.body);
    }
}

#pragma mark = WKNavigationDelegate
//在发送请求之前，决定是否跳转
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *hostname = navigationAction.request.URL.host.lowercaseString;
    NSLog(@"%@",hostname);
    if (navigationAction.navigationType == WKNavigationTypeLinkActivated
        && ![hostname containsString:@".baidu.com"]) {
        // 对于跨域，需要手动跳转
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        
        // 不允许web内跳转
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        self.progressView.alpha = 1.0;
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
}
//在响应完成时，调用的方法。如果设置为不允许响应，web内容就不会传过来

-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    decisionHandler(WKNavigationResponsePolicyAllow);
}
//接收到服务器跳转请求之后调用
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}

//开始加载时调用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
//当内容开始返回时调用
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
//页面加载完成之后调用
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//    NSLog(@"title:%@",webView.title);
    
    //这个方法也可以计算出webView滚动视图滚动的高度
//    [webView evaluateJavaScript:@"document.body.scrollWidth"completionHandler:^(id _Nullable result,NSError * _Nullable error){
//
//        NSLog(@"scrollWidth高度：%.2f",[result floatValue]);
//        CGFloat ratio =  CGRectGetWidth(self.webView.frame) /[result floatValue];
//
//        [webView evaluateJavaScript:@"document.body.scrollHeight"completionHandler:^(id _Nullable result,NSError * _Nullable error){
//            NSLog(@"scrollHeight高度：%.2f",[result floatValue]);
////            NSLog(@"scrollHeight计算高度：%.2f",[result floatValue]*ratio);
////            CGFloat newHeight = [result floatValue]*ratio;
//            CGFloat newHeight = [result floatValue];
//
//            [self resetWebViewFrameWithHeight:newHeight];
//
//            float leftHeight = SCREEN_HEIGHT-_studeyBgView.bottom-20;
//            if (newHeight < leftHeight) {
//                //如果webView此时还不是满屏，就需要监听webView的变化  添加监听来动态监听内容视图的滚动区域大小
//                [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
//            }
//        }];
//
//    }];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    
}

#pragma mark WKUIDelegate

//alert 警告框
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"调用alert提示框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    NSLog(@"alert message:%@",message);
    
}

//confirm 确认框
-(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认框" message:@"调用confirm提示框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
    
    NSLog(@"confirm message:%@", message);
    
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"输入框" message:@"调用输入框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor blackColor];
    }];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([[alert.textFields lastObject] text]);
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
}

- (void)addTitle{
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(10, KNavFullHeight+10, SCREEN_WIDTH-20, 40)];
    _titlelab = titleLab;
    titleLab.numberOfLines = 0;
    titleLab.text = self.titleString;
    titleLab.textColor = kTitleColor_black;
    titleLab.font = [UIFont boldSystemFontOfSize:16];
    float width = [PublicUtils getLabelWidthWithString:titleLab.text font:titleLab.font];
    if(width < titleLab.width){
        titleLab.textAlignment = NSTextAlignmentCenter;
    }
    [self.view addSubview:titleLab];
}


- (InformationModel *)infoModel{
    
    if (nil == _infoModel) {
        _infoModel = [[InformationModel alloc]initWithDelegate:self cache:NO];
    }
    return _infoModel;
}

- (NSArray *)fontArray{
    if(nil == _fontArray){
        _fontArray = @[@"font-size: 12px",@"font-size: 13px",@"font-size: 14px",@"font-size: 15px",@"font-size: 16px",@"font-size: 17px",@"font-size: 18px",@"font-size: 19px",@"font-size: 20px",@"font-size: 21px",@"font-size: 22px",@"font-size: 23px",@"font-size: 24px",@"font-size: 25px"];
    }
    return _fontArray;
}

- (NSArray *)lineHeightArray{
    if(nil == _lineHeightArray){
        _lineHeightArray = @[@"line-height: 20px",@"line-height: 21px",@"line-height: 22px",@"line-height: 23px",@"line-height: 24px",@"line-height: 25px",@"line-height: 26px",@"line-height: 27px",@"line-height: 28px",@"line-height: 29px",@"line-height: 30px",@"line-height: 31px",@"line-height: 32px",@"line-height: 33px",];
    }
    return _lineHeightArray;
}

- (AddStudyTimeModel *)addStudyModel{
    if (nil == _addStudyModel) {
        _addStudyModel = [[AddStudyTimeModel alloc]initWithDelegate:self cache:NO];
    }
    return _addStudyModel;
}
@end
